const dotenv = require("dotenv")
dotenv.config()
const express = require('express');
const request = require('./request.js');
const bodyParser = require('body-parser')

const app = express();
const port = 4000;

app.use(bodyParser.json())

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, POST');
    res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
    next();
});

app.post('/getImgSrc', async (req, res) => {
    try {
        const path = req.body?.path;
        if (!path){
            throw new Error();
        }
        const response = await request.get(path, {
            responseType: 'arraybuffer',
        });

        const imgData = Buffer.from(response.data, 'binary').toString('base64');

        res.send(`data:image/jpg;base64,${imgData}`);
    } catch (error) {
        res.status(500).send('Error occurred while fetching image');
    }
});

app.listen(port, () => {
    console.log('Server is running on port ' + port);
});
